package com.paradise.phone.utils;

import android.app.DownloadManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;

import com.paradise.phone.bean.UpdateInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Sisyphus on 2017/9/29.
 */

public class UpdateManager {

    private static UpdateManager updateManager;
    private Context context;

    private UpdateManager(){}

    private UpdateManager(Context context){
        this.context = context;
    }

    public static UpdateManager getInstance(Context context){
        if (updateManager == null){
            synchronized (UpdateManager.class) {
                if (updateManager == null) {
                    updateManager = new UpdateManager(context);
                }
            }
        }

        return updateManager;
    }

    public String getUpdateInfo(String httpUrl){
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean isNeedUpdate(UpdateInfo info) {
        if (info == null)
            return false;

        PackageManager manager = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        int currentVersion = packageInfo.versionCode;
        int updateVersion = info.getVersionCode();

        if (currentVersion < updateVersion){
            return true;
        }else {
            return false;
        }

    }

    public long downLoadAPK(String url) {

        if (TextUtils.isEmpty(url)) {
            return -1;
        }

        try {
            String serviceString = Context.DOWNLOAD_SERVICE;
            final DownloadManager downloadManager = (DownloadManager) context.getSystemService(serviceString);

            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);
            request.allowScanningByMediaScanner();
            request.setVisibleInDownloadsUi(true);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setMimeType("application/vnd.android.package-archive");

            File file = new File("paradise/update/", "facephone.apk");
            if (file.exists()) {
                file.delete();
            }
            request.setDestinationInExternalPublicDir("paradise/update/", "facephone.apk");
            long reference = downloadManager.enqueue(request);
            SharedPreferences preferences = context.getSharedPreferences("face_phone", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putLong("reference", reference);
            editor.commit();
            ToastUtil.showToast(context, "开始下载更新");
            return reference;
        } catch (Exception exception) {
            return -1;
        }

    }

}
